const express = require('express');
const router = express.Router();
const path = require('path');

router.post('/upload', async (req, res) => {
    try {
        if (!req.files || Object.keys(req.files).length === 0) {
            return res.status(400).json({
                success: false,
                message: '没有上传文件'
            });
        }

        const file = req.files.file;

        // 验证文件类型
        if (!file.name.toLowerCase().endsWith('.csv')) {
            return res.status(400).json({
                success: false,
                message: '只能上传CSV文件'
            });
        }

        // 验证文件大小（100MB）
        const maxSize = 100 * 1024 * 1024;
        if (file.size > maxSize) {
            return res.status(400).json({
                success: false,
                message: '文件大小不能超过100MB'
            });
        }

        // 修改上传路径到upload目录
        const uploadPath = path.join(__dirname, '../upload/', file.name);

        // 确保目标目录存在
        const fs = require('fs');
        const targetDir = path.dirname(uploadPath);
        if (!fs.existsSync(targetDir)) {
            fs.mkdirSync(targetDir, { recursive: true });
        }

        file.mv(uploadPath, (err) => {
            if (err) {
                console.error('文件上传错误:', err);
                return res.status(500).json({
                    success: false,
                    message: '文件上传失败'
                });
            }

            res.json({
                success: true,
                message: '文件上传成功',
                filename: file.name,
                filepath: uploadPath
            });
        });
    } catch (error) {
        console.error('上传处理错误:', error);
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
});

module.exports = router;